package com.ruoyi.project.pay;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.Md5Utils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.channel.businessCashChange.domain.BusinessCashChange;
import com.ruoyi.project.channel.businessCashChange.service.IBusinessCashChangeService;
import com.ruoyi.project.channel.businessInfo.domain.BusinessInfo;
import com.ruoyi.project.channel.businessInfo.service.IBusinessInfoService;
import com.ruoyi.project.channel.businessRate.domain.BusinessRate;
import com.ruoyi.project.channel.businessRate.service.IBusinessRateService;
import com.ruoyi.project.channel.channelAccount.domain.ChannelAccount;
import com.ruoyi.project.channel.channelAccount.service.IChannelAccountService;
import com.ruoyi.project.channel.channelAccountAmount.domain.ChannelAccountAmount;
import com.ruoyi.project.channel.channelAccountAmount.service.IChannelAccountAmountService;
import com.ruoyi.project.channel.channelAccountSub.domain.ChannelAccountSub;
import com.ruoyi.project.channel.channelAccountSub.service.IChannelAccountSubService;
import com.ruoyi.project.channel.channelAccountWb.domain.ChannelAccountWb;
import com.ruoyi.project.channel.channelAccountWb.service.IChannelAccountWbService;
import com.ruoyi.project.channel.channelCode.domain.ChannelCode;
import com.ruoyi.project.channel.channelCode.service.IChannelCodeService;
import com.ruoyi.project.channel.channelOrder.domain.ChannelOrder;
import com.ruoyi.project.channel.channelOrder.service.IChannelOrderService;
import com.ruoyi.project.channel.channelSetting.domain.ChannelSetting;
import com.ruoyi.project.channel.channelSetting.service.IChannelSettingService;
import com.ruoyi.project.channel.clientInfo.domain.ClientInfo;
import com.ruoyi.project.channel.clientInfo.service.IClientInfoService;
import com.ruoyi.project.channel.investConfig.domain.InvestConfig;
import com.ruoyi.project.channel.investConfig.service.IInvestConfigService;
import com.ruoyi.project.channel.payerPayType.domain.PayerPayType;
import com.ruoyi.project.channel.payerPayType.service.IPayerPayTypeService;
import com.ruoyi.project.channel.uxInfo.service.IUxInfoService;
import com.ruoyi.project.channel.vwBusinessCashStat.domain.VwBusinessCashStat;
import com.ruoyi.project.channel.vwBusinessCashStat.service.IVwBusinessCashStatService;
import com.ruoyi.project.pay.domain.TempOrder;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;
import io.swagger.annotations.ApiOperation;
import org.aspectj.weaver.loadtime.Aj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 通道订单 服务层实现
 *
 * @author ruoyi
 * @date 2019-04-09
 */
@Service
public class PayServiceImpl {
    @Autowired
    private IChannelOrderService channelOrderService;
    @Autowired
    private IClientInfoService clientInfoService;
    @Autowired
    private IChannelAccountService channelAccountService;
    @Autowired
    private IBusinessInfoService businessInfoService;
    @Autowired
    private IBusinessRateService businessRateService;
    @Autowired
    private IInvestConfigService investConfigService;
    @Autowired
    private IVwBusinessCashStatService vwBusinessCashStatService;
    @Autowired
    private IBusinessCashChangeService businessCashChangeService;
    @Autowired
    private IPayerPayTypeService payerPayTypeService;
    @Autowired
    private PayConfig payConfig;
    @Autowired
    private IUserService userService;
    @Autowired
    private IChannelCodeService channelCodeService;
    @Autowired
    private ThirdPayerServiceImpl thirdPayerService;
    @Autowired
    private PayVnetServiceImpl payVnetService;
    @Autowired
    private IChannelAccountAmountService channelAccountAmountService;
    @Autowired
    private IChannelSettingService channelSettingService;
    @Autowired
    private IChannelAccountSubService channelAccountSubService;
    @Autowired
    private IChannelAccountWbService channelAccountWbService;
    @Autowired
    private IUxInfoService uxInfoService;
    private static final Logger log = LoggerFactory.getLogger(PayServiceImpl.class);

    private String parseNullString(String value) {
        if (value == null) {
            return "";
        }
        return value;
    }

    /**
     * 获取超期时间
     *
     * @param date
     * @return
     */
    public String getExpiredTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MINUTE, 4);// 24小时制   
        date = cal.getTime();
        return format.format(date);
    }

    /**
     * 添加订单
     *
     * @param channelOrder
     * @param formOrder    为了兼容别的系统而做的接口(森火)
     * @return
     */
    public AjaxResult addOrder(ChannelOrder channelOrder, TempOrder formOrder) {
        channelOrder.setOrderAmount(channelOrder.getAmount());
        String requestUrl = ServletUtils.getRequest().getRequestURL().toString();
        if (!requestUrl.contains("badatong.vip")) {
            log.info(channelOrder.getBusinessId() + ":" + ServletUtils.getRequest().getRequestURL().toString());
        }

        log.info("addOrder channelOrder:" + channelOrder.toString());
        // 获取商户信息
        BusinessInfo businessInfo = businessInfoService.selectBusinessInfoById(channelOrder.getBusinessId());
        User user = userService.selectUserById(businessInfo.getBusinessId());
        if (user.getStatus().equals("1")) {
            //
            log.error("当前商户已停用");
            return AjaxResult.error("your account can not use!");
        }

        BusinessRate businessRate;
        // 获取商户汇率信息
        BusinessRate searchBusinessRate = new BusinessRate();
        searchBusinessRate.setPayType(channelOrder.getPayType());
        List<BusinessRate> businessRates = businessRateService.selectBusinessRateList(searchBusinessRate);
        if (businessRates.size() == 0) {
            log.info("找不到商户或者商户未开通这种支付方式");
            return AjaxResult.error("The current recharge amount is busy, please try again later!");
        }
        // 如果找到多个随机分配一条
        ArrayList<BusinessRate> tmpBRs = new ArrayList<>();
        for (int m = 0; m < businessRates.size(); m++) {
            BusinessRate tmpB = businessRates.get(m);
            tmpBRs.add(tmpB);
        }
        // 找到哪些系统自带的支付类型需要预充值
        if (tmpBRs.size() == 0) {
            log.info("找不到商户或者商户未开通这种支付方式");
            return AjaxResult.error("The current recharge amount is busy, please try again later!");
        }
        businessRate = tmpBRs.get(new Random().nextInt(tmpBRs.size()));
        // 判断金额范围
        BigDecimal minAmount = businessRate.getMinAmount();
        BigDecimal maxAmount = businessRate.getMaxAmount();
        PayerPayType searchPay = new PayerPayType();
        searchPay.setPayerId(businessRate.getPayerId());
        searchPay.setPayType(businessRate.getPayerPayType());
        List<PayerPayType> payerPayTypes = payerPayTypeService.selectPayerPayTypeList(searchPay);
        PayerPayType payerPayType = payerPayTypes.get(0);
        if (minAmount.compareTo(BigDecimal.valueOf(Long.valueOf("-1"))) == 1 && channelOrder.getAmount().compareTo(minAmount) == -1) {
            // 最小金额 大于-1 用自定义
            log.info("金额不能小于" + minAmount);
            return AjaxResult.error("金额不能小于" + minAmount);
        } else if (minAmount.compareTo(BigDecimal.valueOf(Long.valueOf("-1"))) == 0 && channelOrder.getAmount().compareTo(payerPayType.getMinAmount()) == -1) {
            // 最小金额 -1 继承系统
            log.info("金额不能小于" + payerPayType.getMinAmount());
            return AjaxResult.error("金额不能小于" + payerPayType.getMinAmount());
        } else if (maxAmount.compareTo(BigDecimal.valueOf(Long.valueOf("-1"))) == 0 && channelOrder.getAmount().compareTo(payerPayType.getMaxAmount()) == 1) {
            // 最大金额 -1 继承系统
            log.info("金额不能大于" + payerPayType.getMaxAmount());
            return AjaxResult.error("金额不能大于" + payerPayType.getMaxAmount());
        } else if (maxAmount.compareTo(BigDecimal.valueOf(Long.valueOf("-1"))) == 1 && channelOrder.getAmount().compareTo(maxAmount) == 1) {
            // 最大金额 大于-1 用自定义
            log.info("金额不能大于" + maxAmount);
            return AjaxResult.error("金额不能大于" + maxAmount);
        }
        if (businessInfo.getRootUserId() != null) {
            channelOrder.setAgentUserId(businessInfo.getRootUserId());
        }
        String remark = "真人";
        if(businessInfo.getOrderPrice() != null && businessInfo.getOrderPrice().compareTo(new BigDecimal("100"))== 0){
            remark = "假人";
        }
        channelOrder.setBankName(remark);
        channelOrder.setChannelUserId(businessRate.getChannelId());
        // 支付类型为 支付商的支付类型
        channelOrder.setPayType(businessRate.getPayerPayType());
        channelOrder.setPayerUserId(businessRate.getPayerId());

        List<ChannelAccount> channelAccounts = null;
        channelOrder.setOrderStatus("0");
        channelOrder.setStatus("0");
        String keyup_prefix = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String keyup_append = String.valueOf(new Random().nextInt(899999) + 100000);
        String payOrderid = keyup_prefix + keyup_append;//订单号
        channelOrder.setPtOrderno(payOrderid);
        channelOrder.setChildOrderno(payOrderid);
        channelOrder.setCreateBy(channelOrder.getBusinessId() + "");
//        channelOrder.setChannelUserId(businessInfo.getChannelUserId());
        channelOrder.setBusinessRateId(businessRate.getRateId());

        channelOrderService.insertChannelOrder(channelOrder);
        // 下发订单到支付商
        // 聚合系统的数据要调用下游支付商 ,告诉支付商订单信息 下游支付商返回 支付页面url地址
        JSONObject jsonObject;
        if ("代理中心".equals(businessRate.getPayerUserName())) {
            // 笨鸟支付
//            jsonObject = new JSONObject();
//            JSONObject dataObj = new JSONObject();
//            dataObj.put("payUrl", payConfig.getHost() + "/callback/yangguangView/" + channelOrder.getOrderId());
//            dataObj.put("third", "true");
//            jsonObject.put("data", dataObj);
            jsonObject = thirdPayerService.setToNextOrder(channelOrder, businessRate);
        } else if ("菜鸟".equals(businessRate.getPayerUserName())) {
            // 菜鸟通道
            jsonObject = thirdPayerService.setToNextOrder(channelOrder, businessRate);
        } else if ("系统自带".equals(businessRate.getPayerUserName())) {
            // 系统自带
            jsonObject = new JSONObject();
            JSONObject dataObj = new JSONObject();
            dataObj.put("payUrl", payConfig.getHost() + "/pay/orderView/" + channelOrder.getOrderId());
            jsonObject.put("data", dataObj);
        } else {
            jsonObject = thirdPayerService.setToNextOrder(channelOrder, businessRate);
        }
        JSONObject object = jsonObject.getJSONObject("data");
        if (object == null) {
            return AjaxResult.error("error", "支付商异常");
        }
        String uri = object.getString("payUrl");
        if (uri == null) {
            return AjaxResult.error("error", "支付商异常");
        }
        return AjaxResult.success("success", jsonObject.get("data"));
    }

    /**
     * 下游支付商通知他更新
     *
     * @param channelOrder
     * @return
     */
    @ApiOperation("更新订单")
    public AjaxResult updateOrder(ChannelOrder channelOrder) {
        // 第三方创建订单接口
        // 获取商户信息
        // md5秘钥校验
        doUpdate(channelOrder, "3");
        // 对接上游盘口要更新订单数据了
        channelOrder = channelOrderService.selectChannelOrderById(channelOrder.getOrderId());
        if (channelOrder.getServerUrl() != null && channelOrder.getServerUrl().contains("http")) {
            // 如果有配置这条数据就要通知商户方
            JSONObject jsonObject;
            if ("2".equals(channelOrder.getServerType())) {
                // form 格式
                jsonObject = setToPreOrderByForm(channelOrder);
            } else if ("3".equals(channelOrder.getServerType())) {
                // form 格式
                jsonObject = setToPreOrderByFormSH(channelOrder);
            } else {
                jsonObject = setToPreOrder(channelOrder);
            }
            if (jsonObject == null) {
                return AjaxResult.error("回调上游方失败");
            }
        } else if (channelOrder.getBusinessName().equals("系统商户")) {
            // 入库系统商户库
            updateMoreMoney(channelOrder);
        }
        return AjaxResult.success("success");
    }

    /**
     * 预充值处理
     *
     * @param channelOrder
     */
    public void updateMoreMoney(ChannelOrder channelOrder) {
        ChannelAccountAmount searchAc = new ChannelAccountAmount();
        searchAc.setOrderStatus("0");
        searchAc.setOrderId(channelOrder.getChildOrderno());
        List<ChannelAccountAmount> channelAccountAmounts = channelAccountAmountService.selectChannelAccountAmountList(searchAc);
        if (channelAccountAmounts.size() > 1) {
            log.error("预充值找到多条记录:" + searchAc.toString());
            AjaxResult.error("预充值找到多条记录");
        } else if (channelAccountAmounts.size() == 0) {
            log.error("找不到预充值记录:" + searchAc.toString());
            AjaxResult.error("找不到预充值记录");
        } else {
            ChannelAccountAmount channelAccountAmount = channelAccountAmounts.get(0);
            // 获取码商代理的预付款费率设置
            ChannelSetting searchSetting = new ChannelSetting();
            searchSetting.setChannelId(channelAccountAmount.getChannelUserId());
            searchSetting.setPayType(channelAccountAmount.getPayType());
            List<ChannelSetting> channelSettings = channelSettingService.selectChannelSettingList(searchSetting);
            BigDecimal channelRate = BigDecimal.valueOf(Double.valueOf("-1"));
            if (channelSettings.size() > 0) {
                channelRate = channelSettings.get(0).getDepositRate();
            }
            //  获取当前支付类型的预付款费率
            User user = userService.selectUserByLoginName("系统自带");
            PayerPayType searchPay = new PayerPayType();
            searchPay.setPayerId(user.getUserId());
            searchPay.setPayType(channelAccountAmount.getPayType());
            List<PayerPayType> payerPayTypes = payerPayTypeService.selectPayerPayTypeList(searchPay);
            BigDecimal rate = payerPayTypes.get(0).getDepositRate();
            /// 结果是:-1 小于,0 等于,1 大于
            if (channelRate.compareTo(BigDecimal.valueOf(-1L)) == 0 && rate.compareTo(BigDecimal.valueOf(0L)) == 1) {
                // 跟随系统设置
                BigDecimal re = channelAccountAmount.getPayAmount().add(channelAccountAmount.getPayAmount().multiply(rate));
                channelAccountAmount.setAmount(re);
            } else if (channelRate.compareTo(BigDecimal.valueOf(-1L)) == 1) {
                //  使用通道的自定义费率
                BigDecimal re = channelAccountAmount.getPayAmount().add(channelAccountAmount.getPayAmount().multiply(channelRate));
                channelAccountAmount.setAmount(re);
            } else {
                channelAccountAmount.setAmount(channelAccountAmount.getPayAmount());
            }
            channelAccountAmount.setOrderStatus("1");
            channelAccountAmount.setUpdateTime(new Date());
            if (channelOrder.getOrderStatus().equals("2")) {
                // 补单
                channelAccountAmount.setUpdateBy(ShiroUtils.getLoginName());
            } else {
                channelAccountAmount.setUpdateBy("系统自动");
            }
            channelAccountAmountService.updateChannelAccountAmount(channelAccountAmount);
            // 设置可用金额
            ChannelOrder channelOrder1 = channelOrderService.selectAccountAmountSum(channelAccountAmount.getAccount());
            ChannelAccountAmount channelAccountAmount1 = channelAccountAmountService.selectAccountAmountSum(channelAccountAmount.getAccount());
            ChannelAccount updateAcc = new ChannelAccount();
            updateAcc.setAccount(channelAccountAmount.getAccount());
            updateAcc.setAmount(channelAccountAmount1.getAmount().subtract(channelOrder1.getPayAmount()));
            updateAcc.setPayType(channelAccountAmount1.getPayType());
            int re = channelAccountService.setAmount(updateAcc);
            if (re > 1) {
                log.error("账号配置异常,账号配置多个:" + channelAccountAmount.getAccount());
            }
        }
    }

    /**
     * 调用下游支付商创建订单接口 支付商如果调用成功 必须返回支付uri地址
     *
     * @param channelOrder
     * @return
     */
    public JSONObject setToPreOrder(ChannelOrder channelOrder) {
        String time = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String url = channelOrder.getServerUrl();
        String sign = Util.getMd5Sign(businessInfoService, channelOrder, time);
        RestTemplate restTemplate = new RestTemplate();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("businessId", channelOrder.getBusinessId());
        jsonObject.put("childOrderno", channelOrder.getChildOrderno());
        jsonObject.put("payAmount", parseNullString(channelOrder.getPayAmount() + ""));
        jsonObject.put("orderStatus", "1");
        jsonObject.put("time", time);
        jsonObject.put("sign", sign);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> entity = new HttpEntity<String>(jsonObject.toJSONString(), headers);
        JSONObject body;
        try {
//            if(channelOrder.getBusinessId() ==12395 || channelOrder.getBusinessId() == 12392){
            log.info("回调URL:" + url);
            log.info("回调请求体:" + jsonObject.toJSONString());
            String bodyStr = restTemplate.exchange(url, HttpMethod.POST, entity, String.class).getBody();
            log.info("回调返回数据:" + bodyStr);
            if ("success".equals(bodyStr)) {
                body = new JSONObject();
                body.put("status", 0);
            } else {
                body = JSONObject.parseObject(bodyStr);
            }
//            } else{
//                body = restTemplate.exchange(url, HttpMethod.POST, entity, JSONObject.class).getBody();
//                log.info("上游返回数据:" + body.toJSONString());
//            }
            int status = body.getIntValue("status");

            if (status != 0) {
                channelOrder.setOrderStatus("3");
                channelOrderService.updateChannelOrder(channelOrder);
            }
//            }

        } catch (Exception e) {
            log.error("setToPreOrderError:" + e.getMessage(), e);
            channelOrder.setOrderStatus("3");
            channelOrderService.updateChannelOrder(channelOrder);
            body = null;
        }

        return body;
    }

    /**
     * 调用下游支付商创建订单接口 支付商如果调用成功 必须返回支付uri地址
     *
     * @param channelOrder
     * @return
     */
    public JSONObject setToPreOrderByForm(ChannelOrder channelOrder) {
        String time = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String url = channelOrder.getServerUrl();
        String sign = Util.getMd5Sign(businessInfoService, channelOrder, time);
        JSONObject result;
        try {
            RestTemplate restTemplate = new RestTemplate();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("childOrderno=").append(channelOrder.getChildOrderno());
            stringBuilder.append("&payAmount=").append(parseNullString(channelOrder.getPayAmount() + ""));
            stringBuilder.append("&orderStatus=").append("1");
            stringBuilder.append("&time=").append(time);
            stringBuilder.append("&businessId=").append(channelOrder.getBusinessId());
            stringBuilder.append("&sign=").append(sign);

            log.info("setToPreOrderByForm回调url:" + url);
            String bodyStr;
            if (channelOrder.getBusinessId() == 12482 || channelOrder.getBusinessId() == 12527 || channelOrder.getBusinessId() == 12472 || channelOrder.getBusinessId() == 98 || channelOrder.getBusinessId() == 110
                    || channelOrder.getBusinessId() == 111 ||
                    channelOrder.getBusinessId() == 112 || channelOrder.getBusinessId() == 114 || channelOrder.getBusinessId() == 103
                    || channelOrder.getBusinessId() == 149 || channelOrder.getBusinessId() == 145 || channelOrder.getBusinessId() == 107 || channelOrder.getBusinessId() == 99 || channelOrder.getBusinessId() == 118 || channelOrder.getBusinessId() == 124 || channelOrder.getBusinessId() == 127 || channelOrder.getBusinessId() == 161) {
                stringBuilder.append("&amount=").append(parseNullString(channelOrder.getOrderAmount() + ""));
                log.info("setToPreOrderByForm:" + stringBuilder.toString());
                bodyStr = HttpUtils.sendPost2(url, stringBuilder.toString());
            } else if (channelOrder.getBusinessId() == 140 && payConfig.getTitle().equals("顺恒支付")) {
                log.info("顺恒支付 setToPreOrderByForm:" + stringBuilder.toString());
                System.setProperty("https.protocols", "TLSv1.2,TLSv1.1,SSLv3");
                bodyStr = HttpUtils.sendSSLPost(url, stringBuilder.toString(), "application/x-www-form-urlencoded; charset=utf-8");
            } else {
                if (channelOrder.getBusinessId() == 99) {
                    stringBuilder.append("&amount=").append(parseNullString(channelOrder.getOrderAmount() + ""));
                }
                log.info("setToPreOrderByForm:" + stringBuilder.toString());
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
                HttpEntity entity = new HttpEntity(stringBuilder.toString(), headers);
                bodyStr = restTemplate.exchange(url, HttpMethod.POST, entity, String.class).getBody();
            }
            result = new JSONObject();
            log.info("body:" + bodyStr);
            JSONObject body;
            if ("success".equals(bodyStr.toLowerCase())) {
                body = new JSONObject();
                body.put("status", 0);
            } else {
                body = JSONObject.parseObject(bodyStr);
            }
            int status = body.getIntValue("status");
            if (status != 0) {
                channelOrder.setOrderStatus("3");
                channelOrderService.updateChannelOrder(channelOrder);
            }
        } catch (Exception e) {
            log.error("setToPreOrderByForm:" + e.getMessage(), e);
            channelOrder.setOrderStatus("3");
            channelOrderService.updateChannelOrder(channelOrder);
            result = null;
        }

        return result;
    }

    /**
     * 调用下游支付商创建订单接口 支付商如果调用成功 必须返回支付uri地址
     *
     * @param channelOrder
     * @return
     */
    public JSONObject setToPreOrderByFormSH(ChannelOrder channelOrder) {
        String url = channelOrder.getServerUrl();
        String sign = Util.getMd5SignSH(businessInfoService, channelOrder);
        JSONObject result;
        try {
            RestTemplate restTemplate = new RestTemplate();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("status=").append("1");
            stringBuilder.append("&customerid=").append(parseNullString(channelOrder.getBusinessId() + ""));
            stringBuilder.append("&sdpayno=").append(channelOrder.getPtOrderno());
            stringBuilder.append("&sdorderno=").append(channelOrder.getChildOrderno());
            stringBuilder.append("&total_fee=").append(channelOrder.getPayAmount() + "");
            stringBuilder.append("&paytype=").append(channelOrder.getPayType());
            stringBuilder.append("&remark=").append(channelOrder.getRemark());
            stringBuilder.append("&sign=").append(sign);
            log.info("setToPreOrderByFormSH", stringBuilder.toString());
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            HttpEntity entity = new HttpEntity(stringBuilder.toString(), headers);
            String body = restTemplate.exchange(url, HttpMethod.POST, entity, String.class).getBody();
            log.info("setToPreOrderByFormSH+body", body);
            result = new JSONObject();
//            result = JSONObject.parseObject(body);
//            String status = result.getString("status");
            if (!"success".equals(body)) {
                channelOrder.setOrderStatus("3");
                channelOrderService.updateChannelOrder(channelOrder);
            }
        } catch (Exception e) {
            log.error("setToPreOrderByForm:" + e.getMessage(), e);
            channelOrder.setOrderStatus("3");
            channelOrderService.updateChannelOrder(channelOrder);
            result = null;
        }

        return result;
    }


    /**
     * @param channelOrder
     * @param type         1: 手机端通知订单更新  3: 下游支付商通知订单更新
     * @return
     */
    public AjaxResult doUpdate(ChannelOrder channelOrder, String type) {
        // 获取商户信息
        ChannelOrder order;
        if ("3".equals(type)) {
            // 下游方通知更新订单
            ChannelOrder tmp = new ChannelOrder();
            tmp.setPtOrderno(channelOrder.getOrderId());
            List<ChannelOrder> tmpOrders = channelOrderService.selectChannelOrderList(tmp);
            if (tmpOrders.size() == 0) {
                log.info("找不到商户或者商户未开通这种支付方式");
                return AjaxResult.error("The current recharge amount is busy, please try again later!");
            }
            order = tmpOrders.get(0);
            channelOrder.setOrderId(order.getOrderId());
        } else {
            order = channelOrderService.selectChannelOrderById(channelOrder.getOrderId());
            if (order == null) {
                log.info("找不到订单号");
                return AjaxResult.error("can not found order no!");
            }
        }
        if (order.getSuccessTime() != null) {
            log.info("已经存在订单了,请勿重复提交!");
            return AjaxResult.error("An order already exists, please do not submit it repeatedly!");
        }
        BusinessRate businessRate = businessRateService.selectBusinessRateById(order.getBusinessRateId());
        if (null != businessRate) {
            // 获取支付商费率
            channelOrder.setPayerFee(businessRate.getPayerPayRate().multiply(channelOrder.getPayAmount()));
            // 设置码商费率
            channelOrder.setChannelFee(businessRate.getChannelRate().multiply(channelOrder.getPayAmount()));
            // 设置商户手续费
//            channelOrder.setBusinessFee(businessRate.getPayRate().multiply(channelOrder.getPayAmount()));
        } else {
            // 测试订单
            channelOrder.setBusinessFee(BigDecimal.ZERO);
        }
        // 设置商户费率
        // 先获取配置表信息

        channelOrder.setBusinessFee(BigDecimal.ZERO);

        channelOrder.setSuccessTime(new Date());
        if (!"2".equals(channelOrder.getOrderStatus()) && !"3".equals(channelOrder.getOrderStatus())) {
            // 如果已经设置了2状态, 则不要再重新设置状态
            channelOrder.setOrderStatus("1");
        }

        // 记录资金变更记录
        BusinessCashChange change = new BusinessCashChange();
        change.setBusinessId(order.getBusinessId());
        change.setAmount(channelOrder.getPayAmount());
        change.setOpType("1");
        change.setPayType(order.getPayType());
        VwBusinessCashStat searchState = new VwBusinessCashStat();
        searchState.setBusinessId(order.getBusinessId());
        List<VwBusinessCashStat> stats = vwBusinessCashStatService.selectVwBusinessCashStatList(searchState);
        if (stats.size() == 0) {
            change.setPreAmount(BigDecimal.ZERO);
        } else {
            change.setPreAmount(stats.get(0).getAmountSum());
        }
        change.setNextAmount(change.getPreAmount().add(change.getAmount()));
        change.setCreateTime(new Date());
        change.setOrderId(order.getPtOrderno());
        change.setRemark("充值订单");
        channelOrderService.updateChannelOrder(channelOrder);


        if (order.getSuccessTime() == null) {
            // 说明之前未记录过了  比如已成功未上分这种,之前已经处理过一次了,则不需要再重新处理
            // 补单不需要更新
            businessCashChangeService.insertBusinessCashChange(change);
        }
        return AjaxResult.success("success");
    }

    /**
     * 手机端收到付款后更新订单
     *
     * @param clientInfo
     * @param time
     * @return
     */
    public AjaxResult updateOrderByPhone(ClientInfo clientInfo, String time) {
        // 手机端成功后更新数据
        List<ChannelOrder> list = new ArrayList<>();
        if (clientInfo.getChannelId().equals("08")) {
            // 钉钉群收款
            list = parseDDChanel(clientInfo);
        } else if (clientInfo.getChannelId().equals("28")) {
            // 淘宝现金红包群收款
            list = parseTBHBChanel(clientInfo, time);
        } else if (clientInfo.getChannelId().equals("29")) {
            // 淘宝现金红包群收款
            list = parseLHQChanel(clientInfo, time);
        } else if (clientInfo.getChannelId().equals("04") || clientInfo.getChannelId().equals("10")) {
            // 短信
            list = parsePhoneChanelSms(clientInfo, time);
            if (list == null) {
                log.error("找不到订单信息");
                return AjaxResult.error("error");
            }
        } else if (clientInfo.getChannelId().equals("11") || clientInfo.getChannelId().equals("17")) {
            // 云闪付
            ChannelOrder channelOrder = parseCloudChanel(clientInfo, time);
            if (channelOrder == null) {
                log.error("找不到订单信息");
                return AjaxResult.error("error");
            }
            list.add(channelOrder);
        } else if (clientInfo.getChannelId().equals("25")) {
            // 企业固码一次金额
            ChannelOrder channelOrder = parseOneGMChanel(clientInfo, time);
            if (channelOrder == null) {
                log.error("找不到订单信息");
                return AjaxResult.error("error");
            }
            list.add(channelOrder);
        } else if (clientInfo.getChannelId().equals("26") || clientInfo.getChannelId().equals("_09")) {
            // 支付宝转账
            ChannelOrder channelOrder = parseZZChanel(clientInfo, time);
            if (channelOrder == null) {
                log.error("找不到订单信息");
                return AjaxResult.error("error");
            }
            list.add(channelOrder);
        } else if (clientInfo.getChannelId().equals("31")) {
            // 支付宝转账
            ChannelOrder channelOrder = parseZZChanel(clientInfo, time);
            if (channelOrder == null) {
                log.error("找不到订单信息");
                return AjaxResult.error("error");
            }
            list.add(channelOrder);
        } else if (clientInfo.getChannelId().equals("20") || clientInfo.getChannelId().equals("21")) {
            // 赞呗
            ChannelOrder channelOrder = parseZanBeiChanel(clientInfo, time);
            if (channelOrder == null) {
                log.error("找不到订单信息");
                return AjaxResult.error("error");
            }
            list.add(channelOrder);
        } else if (clientInfo.getChannelId().equals("27")) {
            // 智享
            ChannelOrder channelOrder = parseZhiXiangChanel(clientInfo, time);
            if (channelOrder == null) {
                log.error("找不到订单信息");
                return AjaxResult.error("error");
            }
            list.add(channelOrder);
        } else if (clientInfo.getChannelId().equals("12")) {
            // 农信易扫
            ChannelOrder channelOrder = parseNXYSChanel(clientInfo, time);
            if (channelOrder == null) {
                log.error("找不到订单信息");
                return AjaxResult.error("error");
            }
            list.add(channelOrder);
        } else if (clientInfo.getChannelId().equals("16") || clientInfo.getChannelId().equals("15_1") || clientInfo.getChannelId().equals("13") || clientInfo.getChannelId().equals("09")) {
            // 中原聚商银行  支付宝固码
            ChannelOrder channelOrder = parseZYBank(clientInfo, time);
            if (channelOrder == null) {
                log.error("找不到订单信息");
                return AjaxResult.error("error");
            }
            list.add(channelOrder);
        } else if (clientInfo.getChannelId().equals("15") || clientInfo.getChannelId().equals("19")) {
            // 微信店员通 微信手机号转账
            ChannelOrder channelOrder = parseWXDYT(clientInfo, time);
            if (channelOrder == null) {
                log.error("找不到订单信息");
                return AjaxResult.error("error");
            }
            list.add(channelOrder);
        } else {
            // 企业号
            ChannelOrder channelOrder = parsePhoneChanel(clientInfo, time);
            if (channelOrder == null) {
                log.error("找不到订单信息");
                return AjaxResult.error("error");
            }
            list.add(channelOrder);
        }
        // 获取商户信息
        for (int i = 0; i < list.size(); i++) {
            ChannelOrder channelOrder = list.get(i);
            channelOrder.setOrderId(channelOrder.getPtOrderno());
            updateOrder(channelOrder);
//            doUpdate(channelOrder, "1");
            // 通知支付中心 成功
//            JSONObject jsonObject = noticeCaiNiao(channelOrder);
//            String code = jsonObject.getString("code");
//            if (code == null || !"0".equals(code)) {
//                // 更新失败
//                channelOrder.setOrderStatus("3");
//                doUpdate(channelOrder, "1");
//            }
        }
        clientInfoService.insertClientInfo(clientInfo);
        return AjaxResult.success("支付回调成功,金额:" + clientInfo.getAmount());
    }

    /**
     * 钉钉
     *
     * @param clientInfo
     * @return
     */
    private List<ChannelOrder> parseDDChanel(ClientInfo clientInfo) {
        List<ChannelOrder> orders = new ArrayList<>();
        String key = "fdfdf#@zXCHP!b9OYFWWW&ViGBcYpLJCRW8nmsFRR";
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(clientInfo.getData());
        stringBuilder.append(key);
        clientInfo.setTime(new Date());
        clientInfo.setCreateTime(new Date());
        boolean b = Md5Utils.vertifyAndroidMD5(stringBuilder.toString(), clientInfo.getSign());
        if (b == false) {
            // 如果校验失败要告警 TODO:
            log.error("parseDDChanel权限校验失败");
            return null;
        }
        try {
            String str = URLDecoder.decode(clientInfo.getData(), "utf-8");
            clientInfo.setData(str);
            JSONObject data = JSONObject.parseObject(str);
            JSONObject subData = data.getJSONObject("data");

            JSONObject groupBillModel = subData.getJSONObject("groupBillModel");
            String masterId = groupBillModel.getString("creatorUid");
            String groupBillId = groupBillModel.getString("groupBillId");
//            String paidAmount = groupBillModel.getString("paidAmount");
            JSONArray groupBillItem = subData.getJSONArray("groupBillItem");
            ArrayList<String> slaveIds = new ArrayList<>();
            String _amount = "0";
            for (int i = 0; i < groupBillItem.size(); i++) {
                JSONObject item = groupBillItem.getJSONObject(i);
                String payStatus = item.getString("payStatus");
                _amount = item.getString("amount");

                if ("0".equals(payStatus)) {
                    // 未付款的忽略掉
                    continue;
                }
                String uid = item.getString("uid");
                slaveIds.add(uid);
            }
            ChannelOrder order = new ChannelOrder();
            // 副号
            order.getParams().put("slaveIds", slaveIds);
            order.setPayType(clientInfo.getChannelId());
            order.setAmount(BigDecimal.valueOf(Double.valueOf(_amount)));
            order.setOrderStatus("0"); // 搜索待支付的订单
            order.setAccountName(groupBillId);
            // 主号
            order.setCardId(masterId);
            List<ChannelOrder> channelOrders = channelOrderService.selectChannelOrderList(order);
            if (channelOrders.size() == 0) {
                clientInfo.setOrderStatus("1");
                clientInfoService.insertClientInfo(clientInfo);
                log.error("找不到主号id为:" + masterId + ";副号" + slaveIds.toString() + ";交易金额" + order.getAmount() + "的工单号");
                return null;
//                return AjaxResult.error("找不到付款方id为:" + clientInfo.getFromUid() + ";交易账号" + clientInfo.getAccount() + ";交易金额" + clientInfo.getAmount() + "的工单号");
            }
            if (channelOrders.size() > 1) {
                clientInfo.setOrderStatus("1");
                clientInfoService.insertClientInfo(clientInfo);
                log.error("找到多个订单号" + masterId + ";" + slaveIds.toString() + ";" + order.getAmount() + ";");
                return null;
            }
            for (int i = 0; i < channelOrders.size(); i++) {
                ChannelOrder ci = channelOrders.get(i);
                ci.setPayAmount(order.getAmount());
            }
            return channelOrders;

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
//            AjaxResult.error("error");
            return null;
        }
    }

    /**
     * 淘宝现金红包
     *
     * @param clientInfo
     * @return
     */
    private List<ChannelOrder> parseTBHBChanel(ClientInfo clientInfo, String money) {
        List<ChannelOrder> orders = new ArrayList<>();
        String signKey = "cainiao666888999";
        String type = clientInfo.getRemark();
        String orderNo = clientInfo.getOrderId();
        String dt = clientInfo.getDeviceNum();
        String no = clientInfo.getAccount();
        boolean b = Md5Utils.vertifyAndroidMD5(type + orderNo + money + dt + no + signKey, clientInfo.getSign());
        if (b == false) {
            // 如果校验失败要告警 TODO:
            log.error("parseTBHBChanel权限校验失败");
            return null;
        }
        ChannelOrder order = new ChannelOrder();
        order.setPayType(clientInfo.getChannelId());
        order.setAmount(BigDecimal.valueOf(Double.valueOf(money)));
        order.setOrderStatus("0"); // 搜索待支付的订单
        order.setAccountName(orderNo);
        List<ChannelOrder> channelOrders = channelOrderService.selectChannelOrderList(order);
        if (channelOrders.size() == 0) {
            clientInfo.setOrderStatus("1");
            clientInfoService.insertClientInfo(clientInfo);
            log.error("找不到id为:" + orderNo + ";交易金额" + order.getAmount() + "的工单号");
            return null;
//                return AjaxResult.error("找不到付款方id为:" + clientInfo.getFromUid() + ";交易账号" + clientInfo.getAccount() + ";交易金额" + clientInfo.getAmount() + "的工单号");
        }
        if (channelOrders.size() > 1) {
            clientInfo.setOrderStatus("1");
            clientInfoService.insertClientInfo(clientInfo);
            log.error("找到多个订单号:" + orderNo + ";" + order.getAmount() + ";");
            return null;
        }
        for (int i = 0; i < channelOrders.size(); i++) {
            ChannelOrder ci = channelOrders.get(i);
            ci.setPayAmount(order.getAmount());
            ci.setAccount(no); // 更新收款账号
        }
        return channelOrders;
    }

    /**
     * 零花钱
     *
     * @param clientInfo
     * @return
     */
    private List<ChannelOrder> parseLHQChanel(ClientInfo clientInfo, String money) {
        List<ChannelOrder> orders = new ArrayList<>();
        String signKey = "cainiaoaaabbb666888";
        String type = clientInfo.getRemark();
        String orderNo = clientInfo.getOrderId();
        String dt = clientInfo.getDeviceNum();
        String no = clientInfo.getAccount();
        boolean b = Md5Utils.vertifyAndroidMD5(money + orderNo + dt + no + signKey, clientInfo.getSign());
        if (b == false) {
            // 如果校验失败要告警 TODO:
            log.error("parseTBHBChanel权限校验失败");
            return null;
        }
        ChannelOrder order = new ChannelOrder();
        order.setPayType(clientInfo.getChannelId());
        order.setAccount(no);
        order.setAmount(BigDecimal.valueOf(Double.valueOf(money)));
        order.setOrderStatus("0"); // 搜索待支付的订单
        List<ChannelOrder> channelOrders = channelOrderService.selectChannelOrderList(order);
        if (channelOrders.size() == 0) {
            clientInfo.setOrderStatus("1");
            clientInfoService.insertClientInfo(clientInfo);
            log.error("找不到id为:" + no + ";交易金额" + order.getAmount() + "的工单号");
            return null;
//                return AjaxResult.error("找不到付款方id为:" + clientInfo.getFromUid() + ";交易账号" + clientInfo.getAccount() + ";交易金额" + clientInfo.getAmount() + "的工单号");
        }
        if (channelOrders.size() > 1) {
            clientInfo.setOrderStatus("1");
            clientInfoService.insertClientInfo(clientInfo);
            log.error("找到多个订单号:" + no + ";" + order.getAmount() + ";");
            return null;
        }
        for (int i = 0; i < channelOrders.size(); i++) {
            ChannelOrder ci = channelOrders.get(i);
            ci.setPayAmount(order.getAmount());
        }
        return channelOrders;
    }

    /**
     * 企业号
     *
     * @param clientInfo
     * @param time
     * @return
     */
    private ChannelOrder parsePhoneChanel(ClientInfo clientInfo, String time) {
        String key = "fdfdf#@zXCHP!b9OYFWWW&ViGBcYpLJCRW8nmsFRR";
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("");
        stringBuilder.append(time);
        stringBuilder.append(key);
        Date date = new Date();
        date.setTime(Long.parseLong(time + "000"));
        clientInfo.setTime(date);
        clientInfo.setCreateTime(new Date());
        boolean b = Md5Utils.vertifyAndroidMD5(stringBuilder.toString(), clientInfo.getSign());
        if (b == false) {
            // 如果校验失败要告警 TODO:
            log.error("parsePhoneChanel权限校验失败");
            return null;
        }
        try {
            String decodeUrl;
            if (clientInfo.getType().equals("list")) {
                // 列表
                decodeUrl = clientInfo.getOrderList();
            } else {
                decodeUrl = clientInfo.getData();
            }
            String str = URLDecoder.decode(decodeUrl, "utf-8");
            clientInfo.setData(str);
            if (clientInfo.getType().equals("list")) {
                JSONArray array = JSONObject.parseArray(str);
                JSONObject object = array.getJSONObject(0);
                String amount_ = object.getString("price");
                double amount = Double.valueOf(amount_);
                clientInfo.setAmount(BigDecimal.valueOf(amount));
                if (amount < 0) {
                    log.error("订单金额小于0:交易账号" + clientInfo.getAccount() + ";交易金额" + clientInfo.getAmount() + "的工单号");
                    return null;
                }
                long payTime = object.getLongValue("pay_time");
                long diff = (System.currentTimeMillis() - payTime) / 1000;
                if (diff > 30) {
                    // 大于30秒不入库  直接掉单
                    log.error("订单时间大于30秒:交易账号" + clientInfo.getAccount() + ";交易金额" + clientInfo.getAmount() + "的工单号");
                    return null;
                }
            } else {
                JSONObject data = JSONObject.parseObject(str);
                clientInfo.setAmount(data.getBigDecimal("amount"));
                if (clientInfo.getAction().equals("rec_packet_info")) {
                    clientInfo.setFromUid(data.getString("fromUId"));
                    JSONObject tmp = JSONObject.parseObject(data.getString("templateData"));
                    clientInfo.setOrderId(tmp.getString("m"));
                } else if (clientInfo.getAction().equals("transfer_accounts")) {
                    clientInfo.setFromUid(data.getString("fromUId"));
                    clientInfo.setOrderId(data.getString("orderId"));
                }
            }
            ChannelOrder order = new ChannelOrder();
//            order.setFromAlipayId(clientInfo.getFromUid());
            order.setAccount(clientInfo.getAccount());
            order.setPayType(clientInfo.getChannelId());
            order.setAmount(clientInfo.getAmount());
            order.setOrderStatus("0"); // 搜索待支付的订单
            List<ChannelOrder> channelOrders = channelOrderService.selectChannelOrderListOrderByCreateTime(order);
            if (channelOrders.size() == 0) {
                clientInfo.setOrderStatus("1");
                clientInfoService.insertClientInfo(clientInfo);
                log.error("找不到付款方id为:" + clientInfo.getFromUid() + ";交易账号" + clientInfo.getAccount() + ";交易金额" + clientInfo.getAmount() + "的工单号");
                return null;
//                return AjaxResult.error("找不到付款方id为:" + clientInfo.getFromUid() + ";交易账号" + clientInfo.getAccount() + ";交易金额" + clientInfo.getAmount() + "的工单号");
            }
            if (channelOrders.size() > 1) {
                clientInfo.setOrderStatus("1");
                clientInfoService.insertClientInfo(clientInfo);
                log.error("找到多个订单号" + clientInfo.getChannelId() + ";" + order.getCardId() + ";" + order.getAmount() + ";");
                return null;
            }
            channelOrders.get(0).setPayAmount(order.getAmount());
            return channelOrders.get(0);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
//            AjaxResult.error("error");
            return null;
        }
    }

    /**
     * 短信解析
     *
     * @param clientInfo
     * @param time
     * @return
     */
    private List<ChannelOrder> parsePhoneChanelSms(ClientInfo clientInfo, String time) {
        String key = "fdfdf#@zXCHP!b9OYFWWW&ViGBcYpLJCRW8nmsFRR";
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(time);
        stringBuilder.append(key);
        boolean b = Md5Utils.vertifyAndroidMD5(stringBuilder.toString(), clientInfo.getSign());
        if (b == false) {
            // 如果校验失败要告警 TODO:
            log.error("parsePhoneChanelSms权限校验失败");
            return null;
        }
        Date date = new Date();
        date.setTime(Long.parseLong(time + "000"));
        clientInfo.setTime(date);
        clientInfo.setCreateTime(new Date());
        ArrayList<JSONObject> smsInfos = JSONObject.parseObject(clientInfo.getOrderList(), ArrayList.class);
        if (smsInfos.size() == 0) {
            log.error("没有短信信息");
            return null;
        }
        List<ChannelOrder> orders = new ArrayList<>();
        for (int i = 0; i < smsInfos.size(); i++) {
            ChannelOrder order = new ChannelOrder();
            log.info("短信内容:" + smsInfos.get(i));
            JSONObject object = smsInfos.get(0);
            order.setPhoneNo(object.getString("mobilePhone"));
            order.setBankMessageNo(object.getString("sender"));
            long smsTime = object.getLongValue("smsTime");
            long diff = System.currentTimeMillis() - smsTime;
            if (diff > 1000 * 60 * 10) {
                // 只处理误差10分钟内的单子
                continue;
            }
            BigDecimal amount = BankSmsMessage.getAmount(order.getBankMessageNo(), object);
            if (amount == null) {
                continue;
            }
            order.setOrderStatus("0"); // 搜索待支付的订单
            order.setPayType(clientInfo.getChannelId());
            order.setAmount(amount);
//            order.getParams().put("amounts", amounts);
            order.getParams().put("minus", "1");
            List<ChannelOrder> channelOrders = channelOrderService.selectChannelOrderList(order);
            if (channelOrders.size() > 1) {
                log.error("找到多个订单号" + clientInfo.getChannelId() + ";" + order.getPhoneNo() + ";" + order.getAmount() + ";" + order.getBankMessageNo());
                return null;
            }
            for (int j = 0; j < channelOrders.size(); j++) {
                channelOrders.get(j).setPayAmount(channelOrders.get(j).getAmount());
                orders.add(channelOrders.get(j));
            }
        }
        if (orders.size() == 0) {
            clientInfo.setOrderStatus("1");
            clientInfo.setData(smsInfos.toString());
            clientInfoService.insertClientInfo(clientInfo);
            log.error("匹配不到订单号" + clientInfo.getChannelId() + ";" + smsInfos.toString());
            return null;
        }
        return orders;
    }

    /**
     * 短信解析
     *
     * @param clientInfo
     * @param time
     * @return
     */
    private ChannelOrder parseZYBank(ClientInfo clientInfo, String time) {
        if ("15_1".equals(clientInfo.getChannelId())) {
            clientInfo.setChannelId("15");
        }
        String key = "SAFTTSFSDFHNMHWERTASDFGFSDGTU656DSVSFBBGNMZXFUYUI987865";
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(time);
        stringBuilder.append(key);
        boolean b = Md5Utils.vertifyAndroidMD5(stringBuilder.toString(), clientInfo.getSign());
        if (b == false) {
            // 如果校验失败要告警 TODO:
            log.error("parseZYBank权限校验失败");
            return null;
        }

        ChannelOrder order = new ChannelOrder();
        order.setAccount(clientInfo.getAccount());
        order.setPayType(clientInfo.getChannelId());
        order.setAmount(clientInfo.getAmount());
        order.setOrderStatus("0"); // 搜索待支付的订单
        List<ChannelOrder> channelOrders = channelOrderService.selectChannelOrderListOrderByCreateTime(order);
        if (channelOrders.size() == 0) {
            clientInfo.setOrderStatus("1");
            clientInfoService.insertClientInfo(clientInfo);
            log.error("找不到付款方id为:" + clientInfo.getFromUid() + ";交易账号" + clientInfo.getAccount() + ";交易金额" + clientInfo.getAmount() + "的工单号");
            return null;
        }
        if (channelOrders.size() > 1) {
            clientInfo.setOrderStatus("1");
            clientInfoService.insertClientInfo(clientInfo);
            log.error("找到多个订单号" + clientInfo.getChannelId() + ";" + order.getCardId() + ";" + order.getAmount() + ";");
            return null;
        }
        channelOrders.get(0).setPayAmount(order.getAmount());
        return channelOrders.get(0);
    }

    /**
     * 短信解析
     *
     * @param clientInfo
     * @param money
     * @return
     */
    private ChannelOrder parseWXDYT(ClientInfo clientInfo, String money) {
        String key = "cainiao999999";
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(clientInfo.getType());
        stringBuilder.append(money);
        stringBuilder.append(clientInfo.getDeviceNum()); // time
        if (clientInfo.getChannelId().equals("15")) {
            stringBuilder.append(clientInfo.getFromName()); // no
        } else {
            stringBuilder.append(clientInfo.getAccount()); // no
        }

        stringBuilder.append(key);
        boolean b = Md5Utils.vertifyAndroidMD5(stringBuilder.toString(), clientInfo.getSign());
        if (b == false) {
            // 如果校验失败要告警 TODO:
            log.error("parseWXDYT权限校验失败");
            return null;
        }
        clientInfo.setType("");
        ChannelOrder order = new ChannelOrder();
        order.setAccount(clientInfo.getAccount());
        order.setPayType(clientInfo.getChannelId());
        order.setAmount(clientInfo.getAmount());
        order.setOrderStatus("0"); // 搜索待支付的订单
        List<ChannelOrder> channelOrders = channelOrderService.selectChannelOrderListOrderByCreateTime(order);
        if (channelOrders.size() == 0) {
            clientInfo.setOrderStatus("1");
            clientInfoService.insertClientInfo(clientInfo);
            log.error("找不到付款方id为:" + clientInfo.getFromUid() + ";交易账号" + clientInfo.getAccount() + ";交易金额" + clientInfo.getAmount() + "的工单号");
            return null;
        }
        if (channelOrders.size() > 1) {
            clientInfo.setOrderStatus("1");
            clientInfoService.insertClientInfo(clientInfo);
            log.error("找到多个订单号" + clientInfo.getAccount() + ";" + order.getCardId() + ";" + order.getAmount() + ";");
            return null;
        }
        channelOrders.get(0).setPayAmount(order.getAmount());
        return channelOrders.get(0);
    }

    public AjaxResult channelList(ChannelOrder channelOrder) {
        BusinessInfo businessInfo = businessInfoService.selectBusinessInfoById(channelOrder.getBusinessId());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("businessId=").append(channelOrder.getBusinessId());
        stringBuilder.append("&childOrderno=").append(channelOrder.getChildOrderno());
        stringBuilder.append("&time=").append(channelOrder.getTime());
        stringBuilder.append("&").append(businessInfo.getApiKey());
        System.out.println("channelList:" + stringBuilder.toString());
        boolean b = Md5Utils.vertifyAndroidMD5(stringBuilder.toString(), channelOrder.getSign());
        if (b == false) {
            // 如果校验失败要告警 TODO:
            return AjaxResult.error("鉴权失败");
        }
        List<ChannelOrder> list = channelOrderService.selectChannelOrderList(channelOrder);
        return AjaxResult.success("success", list);
    }


    /**
     * 云闪付
     *
     * @param clientInfo
     * @return
     */
    private ChannelOrder parseCloudChanel(ClientInfo clientInfo, String price) {
        String key = "cainiao666";
        String temp = clientInfo.getOrderId() + price + clientInfo.getRemark() + clientInfo.getAccount() + key;
//        if (clientInfo.getType() == null) {
//            temp = clientInfo.getOrderId() + price + clientInfo.getAccount() + key;
//        }
        boolean b = Md5Utils.vertifyAndroidMD5(temp, clientInfo.getSign());
        if (b == false) {
            // 如果校验失败要告警 TODO:
            log.error("parsePhoneChanel权限校验失败");
            return null;
        }
        ChannelOrder order = new ChannelOrder();
        order.setAccount(clientInfo.getAccount());
        order.setPayType(clientInfo.getChannelId());
        order.setAmount(clientInfo.getAmount());
        order.setOrderStatus("0"); // 搜索待支付的订单
        List<ChannelOrder> channelOrders = channelOrderService.selectChannelOrderListOrderByCreateTime(order);
        if (channelOrders.size() == 0) {
            clientInfo.setOrderStatus("1");
            clientInfoService.insertClientInfo(clientInfo);
            log.error("找不到付款方id为:" + clientInfo.getOrderId() + ";交易账号" + clientInfo.getAccount() + ";交易金额" + clientInfo.getAmount() + "的工单号");
            return null;
        }
        if (channelOrders.size() > 1) {
            clientInfo.setOrderStatus("1");
            clientInfoService.insertClientInfo(clientInfo);
            log.error("找到多个订单号" + clientInfo.getChannelId() + ";" + order.getCardId() + ";" + order.getAmount() + ";");
            return null;
        }
        channelOrders.get(0).setPayAmount(order.getAmount());
        return channelOrders.get(0);
    }

    /**
     * 支付宝企业固码
     *
     * @param clientInfo
     * @return
     */
    private ChannelOrder parseOneGMChanel(ClientInfo clientInfo, String price) {
        String key = "cainiao888888";
        // userId + money + orderNo + time + no + key
        String temp = clientInfo.getFromUid() + price + clientInfo.getOrderId() + clientInfo.getDeviceNum() + clientInfo.getAccount() + key;
        boolean b = Md5Utils.vertifyAndroidMD5(temp, clientInfo.getSign());
        if (b == false) {
            // 如果校验失败要告警 TODO:
            log.error("parseOneGMChanel");
            return null;
        }
        ChannelOrder order = new ChannelOrder();
        order.setAccount(clientInfo.getAccount());
        order.setPayType(clientInfo.getChannelId());
        order.setOrderId(clientInfo.getRemark());
        order.setAmount(clientInfo.getAmount());
        order.setOrderStatus("0"); // 搜索待支付的订单
        List<ChannelOrder> channelOrders = channelOrderService.selectChannelOrderListOrderByCreateTime(order);
        if (channelOrders.size() == 0) {
            clientInfo.setOrderStatus("1");
            clientInfoService.insertClientInfo(clientInfo);
            log.error("找不到付款方id为:" + clientInfo.getOrderId() + ";交易账号" + clientInfo.getAccount() + ";交易金额" + clientInfo.getAmount() + "的工单号");
            return null;
        }
        if (channelOrders.size() > 1) {
            clientInfo.setOrderStatus("1");
            clientInfoService.insertClientInfo(clientInfo);
            log.error("找到多个订单号" + clientInfo.getChannelId() + ";" + order.getCardId() + ";" + order.getAmount() + ";");
            return null;
        }
        channelOrders.get(0).setPayAmount(order.getAmount());
        return channelOrders.get(0);
    }

    /**
     * 支付宝转账
     *
     * @param clientInfo
     * @return
     */
    private ChannelOrder parseZZChanel(ClientInfo clientInfo, String price) {
        String key = "cainiao888888";
        // userId + money + orderNo + time + no + key
        String temp = clientInfo.getFromUid() + price + clientInfo.getOrderId() + clientInfo.getDeviceNum() + clientInfo.getAccount() + key;
        boolean b = Md5Utils.vertifyAndroidMD5(temp, clientInfo.getSign());
        if (b == false) {
            // 如果校验失败要告警 TODO:
            log.error("parseOneGMChanel");
            return null;
        }
        ChannelOrder order = new ChannelOrder();
        order.setAccount(clientInfo.getAccount());
        order.setPayType(clientInfo.getChannelId().replace("_", ""));
        order.setAmount(clientInfo.getAmount());
        order.setOrderStatus("0"); // 搜索待支付的订单
        List<ChannelOrder> channelOrders = channelOrderService.selectChannelOrderListOrderByCreateTime(order);
        if (channelOrders.size() == 0) {
            clientInfo.setOrderStatus("1");
            clientInfoService.insertClientInfo(clientInfo);
            log.error("找不到付款方id为:" + clientInfo.getOrderId() + ";交易账号" + clientInfo.getAccount() + ";交易金额" + clientInfo.getAmount() + "的工单号");
            return null;
        }
        if (channelOrders.size() > 1) {
            clientInfo.setOrderStatus("1");
            clientInfoService.insertClientInfo(clientInfo);
            log.error("找到多个订单号" + clientInfo.getChannelId() + ";" + order.getCardId() + ";" + order.getAmount() + ";");
            return null;
        }
        channelOrders.get(0).setPayAmount(order.getAmount());
        return channelOrders.get(0);
    }

    /**
     * 赞呗
     *
     * @param clientInfo
     * @return
     */
    private ChannelOrder parseZanBeiChanel(ClientInfo clientInfo, String price) {
        String key = "kkdfkjsdkfijsdjfhsjlk9899klskdfjhlskjoore09ikwu";
        String temp = clientInfo.getOrderId() + price + clientInfo.getRemark() + clientInfo.getAccount() + key;
        boolean b = Md5Utils.vertifyAndroidMD5(temp, clientInfo.getSign());
        if (b == false) {
            // 如果校验失败要告警 TODO:
            log.error("parsePhoneChanel权限校验失败");
            return null;
        }
        ChannelOrder order = new ChannelOrder();
        order.setAccount(clientInfo.getAccount());
        order.setPayType(clientInfo.getChannelId());
        order.setAmount(clientInfo.getAmount());
        order.setOrderStatus("0"); // 搜索待支付的订单
        List<ChannelOrder> channelOrders = channelOrderService.selectChannelOrderListOrderByCreateTime(order);
        if (channelOrders.size() == 0) {
            clientInfo.setOrderStatus("1");
            clientInfoService.insertClientInfo(clientInfo);
            log.error("找不到付款方id为:" + clientInfo.getOrderId() + ";交易账号" + clientInfo.getAccount() + ";交易金额" + clientInfo.getAmount() + "的工单号");
            return null;
        }
        if (channelOrders.size() > 1) {
            clientInfo.setOrderStatus("1");
            clientInfoService.insertClientInfo(clientInfo);
            log.error("找到多个订单号" + clientInfo.getChannelId() + ";" + order.getCardId() + ";" + order.getAmount() + ";");
            return null;
        }
        channelOrders.get(0).setPayAmount(order.getAmount());
        return channelOrders.get(0);
    }

    /**
     * 智享
     *
     * @param clientInfo
     * @return
     */
    private ChannelOrder parseZhiXiangChanel(ClientInfo clientInfo, String price) {
        String key = "kkdfkjsdkfijsdjfhsjlk9899klskdfjhlskjoore09ikwu";
        String temp = clientInfo.getOrderId() + price + clientInfo.getRemark() + clientInfo.getAccount() + key;
        boolean b = Md5Utils.vertifyAndroidMD5(temp, clientInfo.getSign());
        if (b == false) {
            // 如果校验失败要告警 TODO:
            log.error("parsePhoneChanel权限校验失败");
            return null;
        }
        ChannelOrder channelOrder = channelOrderService.selectChannelOrderById(clientInfo.getOrderId());
        if (channelOrder == null) {
            clientInfo.setOrderStatus("1");
            clientInfoService.insertClientInfo(clientInfo);
            log.error("找不到付款方id为:" + clientInfo.getOrderId() + ";交易账号" + clientInfo.getAccount() + ";交易金额" + clientInfo.getAmount() + "的工单号");
            return null;
        }
        if (!channelOrder.getStatus().equals("0")) {
            log.error("id为:" + clientInfo.getOrderId() + ";交易账号" + clientInfo.getAccount() + ";交易金额" + clientInfo.getAmount() + "的工单号已经成功或者超时");
            return null;
        }
        channelOrder.setPayAmount(clientInfo.getAmount());
        return channelOrder;
    }

    /**
     * 农信易扫
     *
     * @param clientInfo
     * @return
     */
    private ChannelOrder parseNXYSChanel(ClientInfo clientInfo, String price) {
        String key = "cainiao888";
        String temp = clientInfo.getOrderId() + price + clientInfo.getDeviceNum() + key;
        boolean b = Md5Utils.vertifyAndroidMD5(temp, clientInfo.getSign());
        if (b == false) {
            log.error("parseNXYSChanel权限校验失败");
            return null;
        }
        ChannelOrder order = new ChannelOrder();
        order.setAccount(clientInfo.getAccount());
        order.setPayType(clientInfo.getChannelId());
        order.setAmount(clientInfo.getAmount());
        order.setOrderStatus("0"); // 搜索待支付的订单
        List<ChannelOrder> channelOrders = channelOrderService.selectChannelOrderListOrderByCreateTime(order);
        if (channelOrders.size() == 0) {
            clientInfo.setOrderStatus("1");
            clientInfoService.insertClientInfo(clientInfo);
            log.error("找不到付款方id为:" + clientInfo.getOrderId() + ";交易账号" + clientInfo.getAccount() + ";交易金额" + clientInfo.getAmount() + "的工单号");
            return null;
        }
        if (channelOrders.size() > 1) {
            clientInfo.setOrderStatus("1");
            clientInfoService.insertClientInfo(clientInfo);
            log.error("找到多个订单号" + clientInfo.getChannelId() + ";" + order.getCardId() + ";" + order.getAmount() + ";");
            return null;
        }
        channelOrders.get(0).setPayAmount(order.getAmount());
        return channelOrders.get(0);
    }

    public JSONObject queryOrder(TempOrder tempOrder) {
        log.info("temporder:" + tempOrder.toString());
        log.info("tempOrder.getCustomerid():" + tempOrder.getCustomerid());
        BusinessInfo businessInfo = businessInfoService.selectBusinessInfoById(tempOrder.getCustomerid());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("customerid=").append(tempOrder.getCustomerid());
        stringBuilder.append("&sdorderno=").append(tempOrder.getSdorderno());
        stringBuilder.append("&reqtime=").append(tempOrder.getReqtime());
        stringBuilder.append("&").append(businessInfo.getApiKey());
        log.info("queryOrder:" + stringBuilder.toString());
        log.info("queryOrderSign:" + tempOrder.getSign());
        boolean b = Md5Utils.vertifyAndroidMD5(stringBuilder.toString(), tempOrder.getSign());
        if (b == false) {
            // 如果校验失败要告警 TODO:
            log.info("queryOrderSign鉴权失败");
            return new JSONObject();
        }
        ChannelOrder channelOrder = new ChannelOrder();
        channelOrder.setBusinessId(tempOrder.getCustomerid());
        channelOrder.setChildOrderno(tempOrder.getSdorderno());
        List<ChannelOrder> list = channelOrderService.selectChannelOrderList(channelOrder);

        JSONObject result = new JSONObject();
        if (list.size() > 0) {
            ChannelOrder order = list.get(0);
            if (order.getOrderStatus().equals("0") || order.getOrderStatus().equals("4")) {
                result.put("status", 0);
                result.put("msg", "失败订单");
            } else {
                result.put("status", 1);
                result.put("msg", "成功订单");
                result.put("sdorderno", order.getChildOrderno());
                result.put("total_fee", order.getAmount() + "");
                result.put("sdpayno", order.getPtOrderno());
            }
        }
        return result;
    }

    /**
     * @param phones
     * @return
     */
    public AjaxResult validPhones(String phones) {
        JSONObject jsonObject = JSONObject.parseObject(phones);
        phones = jsonObject.getString("phones");
        ChannelAccount searchs = new ChannelAccount();
        searchs.setStatus("0");
        ArrayList<String> _phones = new ArrayList<>();
        String[] phoneStrs = phones.split(",");
        for (int i = 0; i < phoneStrs.length; i++) {
            _phones.add(phoneStrs[i]);
        }
        searchs.getParams().put("accountPhones", _phones);
        List<ChannelAccount> channelAccounts = channelAccountService.selectChannelAccountList(searchs);
        if (channelAccounts.size() != _phones.size()) {
            // 取的大小不一致说明账号有问题
            return AjaxResult.error("账号有问题");
        }
        return AjaxResult.success("账号验证通过");
    }

    /**
     * @param phone
     * @return
     */
    public AjaxResult opcSuccess(String phone) {
        ChannelOrder channelAccountSub = new ChannelOrder();
        channelAccountSub.setAmount(BigDecimal.ONE);
        channelAccountSub.setPayType("09");
        channelAccountSub.setAccount(phone);
        channelAccountSub.setUpdateTime(new Date());
        channelAccountSub.setCreateTime(new Date());
        channelAccountSub.setPayAmount(BigDecimal.ONE);
        channelAccountSub.setOrderStatus("1");
        channelAccountSub.setStatus("0");
        channelAccountSub.setSubmitTime(new Date());
        channelAccountSub.setOrderAmount(BigDecimal.ONE);
        String keyup_prefix = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String keyup_append = String.valueOf(new Random().nextInt(899999) + 100000);
        String payOrderid = keyup_prefix + keyup_append;//订单号
        channelAccountSub.setPtOrderno(payOrderid);
        channelAccountSub.setChildOrderno(payOrderid);
        channelAccountSub.setBusinessId(14L);
        channelAccountSub.setChannelUserId(5L);
        channelOrderService.insertChannelOrder(channelAccountSub);
        return AjaxResult.success(phone + "通知成功");
    }
}
